//
//  GetResultsTableViewController.m
//  消费100
//
//  Created by eliot on 16/3/31.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "GetResultsTableViewController.h"
#import "SubmitDetailTableViewCell.h"
#import "TeamTableViewCell.h"
#import "GetresultTableViewCell.h"
#import "GetResultSecondTableViewCell.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"
@interface GetResultsTableViewController ()


/** 上面数据*/
@property (nonatomic, strong) NSArray *dataArr;


/** 众购记录 数据*/
@property (nonatomic, strong) NSMutableArray *recordArr;

@end

@implementation GetResultsTableViewController

static int pag = 1;

- (void)dealloc {
    pag = 1;
}


- (NSMutableArray *)recordArr {
    if (!_recordArr) {
        _recordArr = [NSMutableArray array];
    }
        return _recordArr;
}

+(GetResultsTableViewController*)CreatGetResultsTableViewController{
    
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    GetResultsTableViewController *GetResultsTableViewController=[story instantiateViewControllerWithIdentifier:@"GetResultsTableViewController"];
    return GetResultsTableViewController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"揭晓结果";
    /** 注册*/
    [self.tableView registerNib:[UINib nibWithNibName:@"SubmitDetailTableViewCell" bundle:nil] forCellReuseIdentifier:@"SubmitDetailTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TeamTableViewCell" bundle:nil] forCellReuseIdentifier:@"TeamTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"GetresultTableViewCell" bundle:nil] forCellReuseIdentifier:@"GetresultTableViewCell"];
     [self.tableView registerNib:[UINib nibWithNibName:@"GetResultSecondTableViewCell" bundle:nil] forCellReuseIdentifier:@"GetResultSecondTableViewCell"];
    self.view.backgroundColor = [UIColor colorWithRed:232/255.0 green:233/255.0 blue:232/255.0 alpha:1];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.navigationController.navigationBar.translucent = NO;
    
    MJRefreshBackGifFooter *footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer = footer;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"crowdfundingId":self.crowdfundingId, @"page":@"1"};
    NSString *baseUrl = [NSString stringWithFormat:@"%@getCrowdfundingById.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            self.dataArr = dic[@"crowdfundingJson"];
            
            self.recordArr = [NSMutableArray arrayWithArray:dic[@"crowdfundingOrderJson"]];
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
    
    
    
}

- (void)loadMoreData {
    pag += 1;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"crowdfundingId":self.crowdfundingId, @"page":@"1"};
    NSString *baseUrl = [NSString stringWithFormat:@"%@getCrowdfundingById.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            [self.tableView.mj_footer endRefreshing];
            [self.recordArr addObjectsFromArray:dic[@"crowdfundingOrderJson"]];
            NSLog(@"*****%@, 商品id= %@", dic, self.crowdfundingId);
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.tableView.mj_footer endRefreshing];
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    }else if (section == 1){
        return self.recordArr.count + 1;
    }else {
        return 1;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
       
        switch (indexPath.row) {
            case 0:
            {
                SubmitDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubmitDetailTableViewCell" forIndexPath:indexPath];
                cell.iconIVW.constant = 90 / 320.0 * Width;
                cell.iconIVH.constant = 100 / 320.0  *Width;
                
                NSDictionary *dic = self.dataArr[0];
                [cell.iconIV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.188:8080/%@", dic[@"img"]]]];
                cell.titleLb.text = dic[@"name"];
                cell.priceLb.hidden = YES;
                return cell;
            }
                break;
            case 1:
            {
                GetresultTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GetresultTableViewCell" forIndexPath:indexPath];
                cell.luckNumberLb.hidden = YES;
                cell.luckyNumberTitleLb.hidden = YES;
                cell.personIDLb.text = self.phoneNum;
                return cell;
            }
                break;
            default:
            {
                GetResultSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GetResultSecondTableViewCell" forIndexPath:indexPath];
                NSDictionary *dic1 = self.dataArr[0][@"startDate"];
                NSDictionary *dic2 = self.dataArr[0][@"endDate"];
                // 时间戳转时间的方法:
                long sendTime1 = [dic1[@"time"] longValue];
                sendTime1 = sendTime1 / 1000;
                NSDate *date1 = [GetResultsTableViewController timeFormatted:sendTime1];
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                //设定时间格式,这里可以设置成自己需要的格式
                [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
                //用[NSDate date]可以获取系统当前时间
                NSString *timeSt1 = [dateFormatter stringFromDate:date1];
                timeSt1 = [timeSt1 stringByReplacingOccurrencesOfString:@"+0000" withString:@""];
                
                
                
                long sendTime2 = [dic2[@"time"] longValue];
                sendTime2 = sendTime2 / 1000;
                NSDate *date2 = [GetResultsTableViewController timeFormatted:sendTime2];
                NSString *timeSt2 = [dateFormatter stringFromDate:date2];
                timeSt2 = [timeSt2 stringByReplacingOccurrencesOfString:@"+0000" withString:@""];
                
                cell.resultTimeLb.text = timeSt2;
                cell.purchasesTimeLb.text = timeSt1;
                
                
                
                
                
                return cell;
            }
                break;
        }
    }else if (indexPath.section == 1) {
        
        
        
        switch (indexPath.row) {
            case 0:
            {
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
                if (!cell) {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
                }
                cell.textLabel.textColor = [UIColor colorWithRed:82/255.0 green:82/255.0 blue:82/255.0 alpha:1];
                cell.textLabel.text = @"所有众购记录";
                UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_arrows"]];
                iv.frame = CGRectMake(0, 0, 12, 12);
                iv.contentMode = UIViewContentModeScaleAspectFit;
                cell.accessoryView = iv;
                cell.detailTextLabel.text = @"查看更多";
                return cell;
            }
                break;
            default:
            {
                TeamTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TeamTableViewCell" forIndexPath:indexPath];
                NSDictionary *dic = self.recordArr[indexPath.row - 1];
                [cell.iconIV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.188:8080/%@", dic[@"img"]]]];
                cell.iconIVW.constant = 52 / 320.0 *Width;
                cell.iconIVH.constant = 52 / 320.0 *Width;
                cell.nameLbTop.constant = 20 / 320.0 *Width;
                cell.nameLb.text = dic[@""];
                //    cell.imageView.image = [UIImage imageNamed:@"BG_MRTX"];
                
                // 时间戳转时间的方法:
                long sendTime1 = [dic[@"inDate"][@"time"] longValue];
                sendTime1 = sendTime1 / 1000;
                NSDate *date1 = [GetResultsTableViewController timeFormatted:sendTime1];
                
                
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                //设定时间格式,这里可以设置成自己需要的格式
                [dateFormatter setDateFormat:@"yyyy-MM-dd"];
                //用[NSDate date]可以获取系统当前时间
                NSString *currentDateStr = [dateFormatter stringFromDate:date1];
                currentDateStr = [currentDateStr stringByReplacingOccurrencesOfString:@"+0000" withString:@""];
                
                cell.phoneNumLb.text = [NSString stringWithFormat:@"众购%@金币 %@", dic[@"coin"], currentDateStr];
                
                return cell;
            }
                break;
        }
    
    }else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"lastCell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"lastCell"];
        }
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [cell addSubview:btn];
        btn.backgroundColor = [UIColor colorWithRed:255/255.0 green:88/255.0 blue:88/255.0 alpha:1];
        [btn setTitle:@"第五期进行中" forState:UIControlStateNormal];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(20);
            make.right.mas_equalTo(-20);
            make.top.mas_equalTo(5);
            make.height.mas_equalTo(35);
        }];
        [btn addTarget:self action:@selector(clickOnZheWayBtn) forControlEvents:UIControlEventTouchUpInside];
        btn.layer.cornerRadius = 8;
        btn.layer.masksToBounds = YES;
        cell.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
        return cell;
    }
    
    
  
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
        {
            if (indexPath.row == 0) {
                return 90 / 320.0 * Width + 15;
            }else if (indexPath.row == 1){
                return 28;
            }else {
                return 65;
            }
        }
            break;
        case 1:
        {
            if (indexPath.row == 0) {
                return 50;
            }else {
                if (Width <= 320) {
                    return 78 / 320.0 *Width;
                }else {
                    return 78 / 320.0 *Width + 4;
                }
            }
        }
            break;
        default:
        {
            return 65 / 320.0 * Width;
        }
            break;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }else if(section == 1){
        return 10;
    }else{
        return 15;
    }
}

/** 时间处理*/
+ (NSDate *)timeFormatted:(long)totalSeconds
{
    
   
    NSDate  *date = [NSDate dateWithTimeIntervalSince1970:totalSeconds];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval:interval];
    return localeDate;
}

/** 点击第三期进行中*/
- (void)clickOnZheWayBtn {



}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
